package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    // 在此方法中使用编程式的事务
    @RequestMapping("/add")
    public int add(UserInfo userInfo) {
        // 非空效验【验证用户名和密码不为空】
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())) return 0;
        // 开启事务（获取事务）
        TransactionStatus transactionStatus =
                transactionManager.getTransaction(transactionDefinition);
        int result = userService.add(userInfo);
        System.out.println("add 受影响的行数：" + result);
        // 提交事务/回滚事务
//        transactionManager.rollback(transactionStatus); // 回滚事务
        transactionManager.commit(transactionStatus);
        return result;
    }

    // 使用声明式事务
    @Transactional // 在方法之前，自动开启事务，在方法执行完之后，自动提交事务，如果出现异常，自动回滚事务
    @RequestMapping("/add2")
    public int add2(UserInfo userInfo) {
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())) return 0;
        int result = userService.add(userInfo);
        System.out.println("add 受影响的行数：" + result);
        return result;
    }

    // 解决try-catch不能回滚
    @Transactional
    @RequestMapping("/add3")
    public int add3(UserInfo userInfo) {
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())) return 0;
        int result = userService.add(userInfo);
        System.out.println("add 受影响的行数：" + result);
        try {
            int num = 10 / 0;
        } catch (Exception e) {
            // 解决办法就是添加下面这一行
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

}
